/* This file is part of LlamaSlayers Ajax Chat
 *
 * The source code is released under the GNU GPL free software license, version 3.
 * Updates can be found at http://llamaslayers-ajax-chat.googlecode.com/
 */

var alt = true,
	focused = true,
	newMessages = 0,
	name = '',
	room = 'public',
	updateRequest,
	onlineRequest,
	timeDiff = 0;

if (!location.hash)
	location.hash = room;
room = location.hash.substr(1).toLowerCase().replace(/[^a-z0-9\-_]/g, '');

document.title = 'Chat (' + room + ')';

$.getScript('name.php');

$(window).focus(function(){
	focused = true;
	newMessages = 0;
	document.title = 'Chat (' + room + ')';
}).blur(function(){
	focused = false;
});

$.get(
	'curtime.php',
	{},
	function(serverTime){
		timeDiff = Math.round(serverTime - new Date / 1000);
	},
	'text'
);

setInterval(function(){
	if (document.title == 'Chat (' + room + ')' && room != location.hash.substr(1)) {
		room = location.hash.substr(1).toLowerCase().replace(/[^a-z0-9\-_]/g, '');
		if (room != location.hash.substr(1))
			location.hash = room;
		document.title = 'Chat (' + room + ')';
		$('h1').text(document.title = 'Chat (' + room + ')');
		$('#online img').remove();
		$('#chat div').hide('slow', function(){
			$(this).remove();
		});
		update();
		updateOnline(true);
		updateChannels();
	}
}, 50);

setInterval(function(){
	if (newMessages) {
		switch (document.title) {
			case 'Chat (' + room + ', ' + newMessages + ' new)':
				document.title = '* Chat (' + room + ', ' + newMessages + ' new) *';
				break;
			case '* Chat (' + room + ', ' + newMessages + ' new) *':
				document.title = '** Chat (' + room + ', ' + newMessages + ' new) **';
				break;
			case '** Chat (' + room + ', ' + newMessages + ' new) **':
				document.title = '*** Chat (' + room + ', ' + newMessages + ' new) ***';
				break;
			case '*** Chat (' + room + ', ' + newMessages + ' new) ***':
				document.title = 'Chat (' + room + ', ' + newMessages + ' new)';
				break;
		}
	}
}, 600);

$.ajaxSetup({
	timeout: 500000
});

function updateTime(element) {
	function time_since(date) {
			function plural(num) {
				if (num != 1)
					return 's';
				return '';
			}
			function numberSuffix(d) {
				d = d + '';
				return d.substr(-Math.min(d.length, 2)) > 3 && d.substr(-(Math.min(d.length, 2))) < 21 ? "th" : ["th", "st", "nd", "rd", "th"][Math.min(+d % 10, 4)];
			}
		var diff = Math.floor(new Date / 1000) - date + timeDiff, _date = new Date(date);
		if (diff == 0)
			return 'Right now';
		if (diff < 60)
			return diff + ' second' + plural(diff) + ' ago';
		diff = Math.floor(diff / 60);
		if (diff < 60)
			return diff + ' minute' + plural(diff) + ' ago';
		diff = Math.floor( diff / 60 );
		if (diff < 24)
			return diff + ' hour' + plural(diff) + ' ago';
		diff = Math.floor(diff / 24);
		if (diff < 7)
			return diff + ' day' + plural(diff) + ' ago';
		diff = Math.floor(diff / 7);
		if (diff < 4)
			return diff + ' week' + plural(diff) + ' ago';
		return 'on ' + _date.toLocaleFormat('%B %e<sup>' + numberSuffix(_date.getDate()) + '</sup>, %Y');
	}

	$(element).html(time_since($(element).data('time')));
	return element;
}

function updateAllTime() {
	$('.time').each(function(){
		updateTime(this);
	});
}
setInterval(updateAllTime, 500);

function update(start) {
	try {
		if (updateRequest)
			updateRequest.abort();
	} catch (ex) {}
	updateRequest = $.get(
		'get.php',
		{ pos: +start, room: room },
		function(abc){
			var messages = abc.split('\n');
			updateRequest = null;
			update(messages[messages.length - 1]);
			delete messages[messages.length - 1];
			messages = $.grep(messages, function(a){
				return a;
			});
			$.each(messages, function(i){
				setTimeout(function(a){
					if (!focused) {
						newMessages++;
						document.title = 'Chat (' + room + ', ' + newMessages + ' new)';
					}
					$('<div/>').addClass((a[0] == '*' ? (function(s) {
						var r = 'chat-verified-';
						var hexes = '0123456789abcdef'.split('');
						for (var i=0; i<s.length; i++) {
							r += hexes[s.toLowerCase().charCodeAt(i) >> 4] + hexes[s.toLowerCase().charCodeAt(i) & 0xf];
						}
						return r;
					})(a.substr(32).split(':')[0]) : 'chat-from-' + a.substr(0, 32)) + ( alt ? ' alt' : '' )).css({
						backgroundColor: alt ? '#fff' : '#f7f7f7',
						fontFamily: 'sans-serif',
						fontSize: a.indexOf(':Global:') != -1 ? '1.25em' : '1em',
						width: '75%'
					}).text(' ' + decodeURIComponent(a.split(':').slice(2).join(':').replace(/\+/g, ' '))).each(function(){
						$(this).html($(this).html().replace(/(^|\s)#([a-zA-Z0-9\-_]+)/g, '$1#<a style="color: #00f" href="#$2">$2</a>'));
						$(this).html($(this).html().replace(/(ht|f)tps?:\/\/((\w+)(:(\w+))?@)?([a-zA-Z0-9\-.]+|\[[a-zA-Z0-9\-.]+\])\.?(:(\d+))?(\/\S*)?/g, function(a){
							return '<a style="color: #11c" target="_blank" href="' + $('<div/>').html(a).text() + '">' + a + '</a>';
						}));
					}).prepend($('<strong/>').text(' ' + decodeURIComponent(a.substr(32).split(':')[0].replace(/\+/g, ' ')) + ':')).prepend($('<img/>').attr({
						src: a[0] == '*' ? 'icons/' + a.substr(1, 31).replace(/^\**/, '') + '_small.png' : 'http://gravatar.com/avatar/' + a.substr(0, 32) + '?d=identicon&s=15&r=d',
						width: 15,
						height: 15
					})).prepend(updateTime($('<span class="time"/>').css({
						fontSize: 'smaller',
						cssFloat: 'right',
						display: 'block',
						margin: 2
					}).data('time', a.split(':')[1]))).hide().appendTo('#chat').show('normal');
					if ($('#chat>div').length > 25)
						$($('#chat>div').get().reverse().slice(25)).hide('slow', function(){
							$(this).remove();
						});
					alt = !alt;
				}, +start > 0 ? i * 500 : 0, this);
			});
		}, 'text'
	);
}
function updateOnline(immediate) {
	try {
		if (onlineRequest)
			onlineRequest.abort();
	} catch (ex) {}
	onlineRequest = $.get(
		'online.php',
		immediate === true ? { immediate: 1, room: room } : { room: room },
		function(abc){
			var users = abc.split('\n');
			$('#online img').remove();
			$.each(users, function(){
				var id = this.substr(0, 33);
				var name = decodeURIComponent(this.split(':')[1].replace(/\+/g, ' '));
				var selector = '.chat-from-' + id.substr(1);
				if (id[0] == '*')
					selector = (function(s) {
						var r = '.chat-verified-';
						var hexes = '0123456789abcdef'.split('');
						for (var i=0; i<s.length; i++) {
							r += hexes[s.toLowerCase().charCodeAt(i) >> 4] + hexes[s.toLowerCase().charCodeAt(i) & 0xf];
						}
						return r;
					})(name);

				$('<img/>').attr({
					src: id[0] == '*' ? 'icons/' + this.split(':')[2] + '_large.png' : 'http://gravatar.com/avatar/' + id.substr(1) + '?d=identicon&s=48&r=d',
					width: 48,
					height: 48,
					title: name,
					alt: name
				}).hover(function(){
					$('.alt' + selector).stop().animate({
						backgroundColor: '#ffb'
					}, 'normal');
					$(selector + ':not(.alt)').stop().animate({
						backgroundColor: '#f7f7bb'
					}, 'normal');
				}, function(){
					$('.alt' + selector).stop().animate({
						backgroundColor: '#fff'
					}, 'normal');
					$(selector + ':not(.alt)').stop().animate({
						backgroundColor: '#f7f7f7'
					}, 'normal');
				}).appendTo('#online');
			});
			onlineRequest = null;
			updateOnline();
		},
		'text'
	);
}
function updateChannels() {
	$.get(
		'channels.php',
		{},
		function(data){
			$('#channels tbody tr').remove();
			var alt = false, channels = data.split(/\n/g);
			$.each(channels, function(){
				var channel = this.split(/:/g);
				if (channel[0] == room)
					return;
				$('<tr/>').css({
					backgroundColor: alt ? '#f7f7f7' : '#fff',
					color: '#333'
				}).hover(function(){
					$(this).stop().animate({
						color: '#000'
					}, 'fast').find('a').stop().animate({
						color: '#00f'
					}, 'fast');
				}, function(){
					$(this).stop().animate({
						color: '#333'
					}, 'fast').find('a').stop().animate({
						color: '#33f'
					}, 'fast');
				}).append($('<th/>').attr({scope: 'row'}).css({
					textAlign: 'left'
				}).text('#').append($('<a/>').text(channel[0]).attr({
					href: '#' + channel[0]
				}).css({
					color: '#33f'
				}))).append(channel[1] != 0 ? updateTime($('<td class="time"/>').data('time', channel[1])) : '<td>Never</td>').append(updateTime($('<td class="time"/>').data('time', channel[2]))).append($('<td/>').html(channel[3])).find('th, td').css({border: '1px solid #ccc'}).end().appendTo('#channels tbody');
				alt = !alt;
			});
		},
		'text'
	);
}
setInterval(updateChannels, 15000);

function promptPassword(name) {
	location.href = 'login.html#' + encodeURIComponent(name);
}

$(function(){
	$('h1').text(document.title = 'Chat (' + room + ')');
	update();
	updateOnline(true);
	updateChannels();
	$('input').css({
		width: '100%'
	});
	$('#right').css({
		width: '25%',
		cssFloat: 'right',
		clear: 'right',
		fontFamily: 'sans-serif'
	});
	$('#online').add('#channels').find('table').css({
		width: '100%',
		outline: '1px solid #333',
		borderCollapse: 'collapse'
	}).find('th').css({
		backgroundColor: '#555',
		color: '#fff',
		border: '1px solid #ddd'
	}).end().end().end().find('h2').css({
		marginTop: 0
	}).add('h1,h2').css({
		fontFamily: 'Impact, sans-serif',
		fontWeight: 'normal'
	});
	$('form').submit(function(){
		if ( $.trim($('input').val()).length )
			$.get(
				'send.php',
				{ message: $('input').val(), room: room }
			);
		$('input').val('');
		return false;
	});
});
var wot_rating_options = {
	updateinterval: 1000
};